<?php

namespace Iwester\Http\Controllers\Admin\Zixun;

use Iwester\Http\Controllers\Admin\BaseController;
use App\Console\Commands\SiteMap;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\Article\ArticleTag;
use Iwester\Http\Requests\ArticleTagStoreRequest;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Article\ArticleCategory;


class AdminTagController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * 资讯 - 标签管理
     * @return Response
     */
    public function tag()
    {
        $tags = ArticleTag::getTags(true);
        return view('iwester::admin.zixun.tag.tag', ['tags'=> $tags]);
    }

    /**
     * 添加标签
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        $tag = $id ? ArticleTag::find($id) : null;
        return view('iwester::admin.zixun.tag.edit', ['tag' => $tag]);
    }

    /**
     * 保存标签
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(ArticleTagStoreRequest $request)
    {
        try {
            \DB::beginTransaction();
            $id = $request->input('id', false);
            $tag = $request->get('tag', []);
            if (isset($tag['status'])) $tag['status'] = (int) $tag['status'];
            if (ArticleTag::checkTag($tag['tag'], $id)) return ['code' => 201, 'message' => '标签已存在'];
            if ($id) {
                if (!isset($tag['status'])) $tag['status'] = 0;
                ArticleTag::find($id)->update($tag);
            } else {
                $tag['user_id'] = \Auth::id();
                ArticleTag::create($tag);
            }
            \DB::commit();
            return ['code' => 200, 'message' => '设置成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => '保存失败！'];
        }
    }
}
